<template>
  <div style="width: 100%;margin: 10px 0 0 0;">
    <el-row v-show="showSearch">
      <el-col class="form_col">
        <el-form :model="queryParams" ref="queryForm" key="terminalDosageQueryForm" :size="formItemSize" v-show="showSearch"
                 :label-width="labelWidth">
          <div style="display: flex; justify-content: start; flex-wrap: wrap;">
            <el-form-item label="分析类型">
              <el-radio-group v-model="queryParams.dataType" size="mini" @change="dataTypeSelectChange">
                <el-radio-button label="1">小时用量</el-radio-button>
                <el-radio-button label="2">日用量</el-radio-button>
                <el-radio-button label="3">月用量</el-radio-button>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="时间间隔" prop="interval" v-if="queryParams.dataType === '1'" style="width: 200px;">
              <el-select v-model="queryParams.interval" placeholder="请选择时间间隔" style="width: 100px;">
                <el-option v-for="(item, index) of realIntervalList" :key="index" :label="item.value"
                           :value="item.key">{{ item.value }}
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="时间选择" prop="timevalue">
              <el-date-picker v-model="timevalue" type="datetimerange" range-separator="至"
                              start-placeholder="开始日期"
                              end-placeholder="结束日期" style="width: 320px;" v-if="queryParams.dataType === '1'"
                              value-format="yyyy-MM-dd HH:mm:ss" :clearable="false"
                              :default-time="['00:00:00', '23:59:59']">
              </el-date-picker>
              <el-date-picker v-model="timevalue" type="daterange" range-separator="至" start-placeholder="开始日期"
                              end-placeholder="结束日期" style="width: 100%;" v-if="queryParams.dataType === '2'"
                              value-format="yyyy-MM-dd" :clearable="false">
              </el-date-picker>
              <el-date-picker v-model="timevalue" type="monthrange" range-separator="至"
                              start-placeholder="开始月份"
                              end-placeholder="结束月份" style="width: 80%;" v-if="queryParams.dataType === '3'"
                              value-format="yyyy-MM" :clearable="false">
              </el-date-picker>
            </el-form-item>
          </div>
        </el-form>
      </el-col>

      <el-col class="form_query">
        <el-button type="primary" @click="handleQuery" size="mini">查询</el-button>
        <el-button @click="resetQuery" size="mini">重置</el-button>
      </el-col>
    </el-row>

    <!--    <el-row :gutter="10" class="mb8">-->
    <!--      <RightDropdown :dayColumns="dayColumns" v-if="queryParams.frozenType==='day'"-->
    <!--                     :showSearch.sync="showSearch" @queryTable="getList"-->
    <!--                     @export="handleExport"></RightDropdown>-->
    <!--      <RightDropdown :dayColumns="monthColumns" v-if="queryParams.frozenType==='month'"-->
    <!--                     :showSearch.sync="showSearch" @queryTable="getList"-->
    <!--                     @export="handleExport"></RightDropdown>-->
    <!--    </el-row>-->

    <el-row>
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="用量数据" name="history">
          <el-table v-loading="loading" :data="dataList" size="mini" border :height="getAvailableHeight" style="margin-top: 10px;">
            <el-table-column v-for="(item, index) in columns" :prop="item.dataIndex" align="center"
                             :show-overflow-tooltip="true" :sortable="item.sortable" :label="item.title"
                             :key="index">
            </el-table-column>
          </el-table>

          <pagination :total="total"
                      :page.sync="queryParams.pageNum"
                      :limit.sync="queryParams.pageSize"
                      @pagination="getList"/>
        </el-tab-pane>

        <el-tab-pane label="图表展示" name="charts" style="margin-top: 10px;">
          <div id="main" ref="main" :style="getChartBoxStyle"></div>
        </el-tab-pane>
      </el-tabs>
    </el-row>
  </div>
</template>

<script>
import moment from "moment/moment";
import * as echarts from "echarts";
import {getPageList, getTerminalDosageList} from "@/api/datastatistics/terminals/dosageStatics";
import {getTwoTimeList, getTwoDayList, getTwoMonth,} from '@/utils/computeDays';

export default {
  name: "Dosage",
  data() {
    return {
      myChart: undefined,
      screenHeight: null,
      loading: false,
      // 显示搜索条件
      showSearch: true,
      collapseAble: false,
      formItemSize: 'mini',
      maxShow: 4,
      labelWidth: '75px',
      // 数据表格数据
      dataList: [],
      // 图表数据
      echartsList: [],
      // tab名称
      activeName: 'history',
      // 总条数
      total: 0,
      // 表头数据
      columns: [
        {title: '采集时间', dataIndex: 'readDateN', width: 200,},
        {title: '正向用量(m³)', dataIndex: 'readDosage', sortable: true},
        {title: '反向用量(m³)', dataIndex: 'reverseDosage', sortable: true},
        {title: '净用量(m³)', dataIndex: 'totalDosage', sortable: true}
      ],
      monthDataList: [],
      monthColumns: [
        // { key: 0, label: `平台主键`, visible: false, dataindex:'ReadGrowthRate' },
        {key: 0, label: `区域名称`, visible: true, dataindex: 'sheetsName'},
        {key: 1, label: `用户编号`, visible: true, dataindex: 'userId'},
        {key: 2, label: `用户名称`, visible: true, dataindex: 'userName'},
        {key: 3, label: `门牌号`, visible: true, dataindex: 'roomName'},
        // { key: 4, label: `表类型`, visible: true, dataindex:'installAddress' },
        {key: 4, label: `设备编号`, visible: true, dataindex: 'terminalId'},
        {key: 5, label: `通讯地址`, visible: true, dataindex: 'communicateAddress'},
        {key: 6, label: `冻结日期`, visible: true, dataindex: 'freezeTime'},
        {key: 7, label: `冻结读数(m³)`, visible: true, dataindex: 'endReading'},
        {key: 8, label: `月用量(m³)`, visible: true, dataindex: 'cumulativeFlow'},
        // { key: 9, label: `实时时间`, visible: true, dataindex:'frozenType' },
      ],
      // 查询参数
       queryParams: {
        pageNum: 1,
        pageSize: 20,
        interval: '',
        dataType: '2',
        location_nb: '',
        startTime: moment().subtract(7, 'days').format('YYYY-MM-DD'),
        endTime: moment().subtract(1, 'days').format('YYYY-MM-DD'),
      },
      // 折线图继承
      chartExtend: {
        // 标题
        title: {
          text: ''
        },
        grid: {
          top: '5%',
          left: '5%',
          right: '5%',
          bottom: '6%',
          containLabel: true,
        },
        // x轴
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: [], // x轴坐标名称
        },
        // y轴
        yAxis: {
          //2022/10 /chuan 原：流量
          name: '用量(m³)',
          type: 'value',
          axisLabel: {
            formatter: '{value} m³'
          }
        },
        // 提示框，鼠标悬浮交互时的信息提示
        tooltip: {
          show: true,
          trigger: 'axis', // 触发类型，默认数据触发，见下图，可选为：'item' | 'axis'
        },
        toolbox: {
          show: true,
          feature: {
            saveAsImage: {}
          }
        },
        legend: {
          data: ['正向用量', '反向用量', '净用量'],
          x: 'center',
          y: 'top',
          show: true,
          padding: 20
        },
        dataZoom: [{
          start: 0,
          end: 100,
          bottom: 10,
          type: 'slider',
          showDataShadow: false,
          handleIcon: 'path://M10.7,11.9v-1.3H9.3v1.3c-4.9,0.3-8.8,4.4-8.8,9.4c0,5,3.9,9.1,8.8,9.4v1.3h1.3v-1.3c4.9-0.3,8.8-4.4,8.8-9.4C19.5,16.3,15.6,12.2,10.7,11.9z M13.3,24.4H6.7V23h6.6V24.4z M13.3,19.6H6.7v-1.4h6.6V19.6z',
          handleSize: '100%'
        }, {
          type: 'inside'
        }],
        // 指定图标的类型
        series: [],
      },
      // 实时时间间隔类型下拉
      realIntervalList: [
        {key: '1', value: '1小时',},
        {key: '2', value: '2小时',},
        {key: '4', value: '4小时',},
        {key: '6', value: '6小时',},
        {key: '12', value: '12小时',},
        {key: '24', value: '24小时',},
      ],
      // 冻结日期
      timevalue: [moment().subtract(7, 'days').format('YYYY-MM-DD'), moment().subtract(1, 'days').format('YYYY-MM-DD')],
    }
  },
  created() {
    this.screenHeight = document.body.clientHeight
    this.handleQuery()
  },
  computed: {
    getAvailableHeight() {
      return this.screenHeight - 315
    },
    getChartBoxStyle() {
      return {width: '100%', height: (this.screenHeight - 280) + 'px'}
    }
  },
  methods: {
    updateLocationNb(locationNb) {
      this.queryParams.location_nb = locationNb
    },
    // 切换tab
    handleClick() {
      if (this.activeName === 'charts') {
        this.$nextTick(() => {
          this.initEchart()
        })
      }
    },
    // 初始化echarts
    initEchart() {
      if (this.myChart) {
        this.myChart.dispose()
      }
      this.myChart = echarts.init(this.$refs.main)
      // this.handleData()
      this.myChart.setOption(this.chartExtend, true)
      this.myChart.resize()
      window.addEventListener('resize', () => {
        this.myChart.resize()
      })
    },
    // 重置图表
    resetEchart() {
      this.chartExtend = {
        // 标题
        title: {
          text: ''
        },
        grid: {
          top: '5%',
          left: '5%',
          right: '5%',
          bottom: '6%',
          containLabel: true,
        },
        // x轴
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: [], // x轴坐标名称
        },
        // y轴
        yAxis: {
          //2022/10 /chuan 原：流量
          name: '用量(m³)',
          type: 'value',
          axisLabel: {
            formatter: '{value} m³'
          }
        },
        // 提示框，鼠标悬浮交互时的信息提示
        tooltip: {
          show: true,
          trigger: 'axis', // 触发类型，默认数据触发，见下图，可选为：'item' | 'axis'
        },
        toolbox: {
          show: true,
          feature: {
            saveAsImage: {}
          }
        },
        legend: {
          data: ['正向用量', '反向用量', '净用量'],
          x: 'center',
          y: 'top',
          show: true,
          padding: 20
        },
        dataZoom: [{
          start: 0,
          end: 100,
          bottom: 10,
          type: 'slider',
          showDataShadow: false,
          handleIcon: 'path://M10.7,11.9v-1.3H9.3v1.3c-4.9,0.3-8.8,4.4-8.8,9.4c0,5,3.9,9.1,8.8,9.4v1.3h1.3v-1.3c4.9-0.3,8.8-4.4,8.8-9.4C19.5,16.3,15.6,12.2,10.7,11.9z M13.3,24.4H6.7V23h6.6V24.4z M13.3,19.6H6.7v-1.4h6.6V19.6z',
          handleSize: '100%'
        }, {
          type: 'inside'
        }],
        // 指定图标的类型
        series: []
      }
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.resetEchart()
      if (this.queryParams.dataType === '1') {
        this.queryParams.startTime = this.timevalue[0]
        this.queryParams.endTime = this.timevalue[1]
        this.columns = [{
          title: '采集时间',
          dataIndex: 'readDateN',
          width: 200
        }, {
          title: '正向用量(m³)',
          dataIndex: 'readDosage'
        }, {
          title: '反向用量(m³)',
          dataIndex: 'reverseDosage'
        }, {
          title: '净用量(m³)',
          dataIndex: 'totalDosage'
        }]
      } else if (this.queryParams.dataType === '2') {
        this.queryParams.startTime = this.timevalue[0]
        this.queryParams.endTime = this.timevalue[1]
        this.columns = [{
          title: '采集时间',
          dataIndex: 'readDateDay',
          width: 200
        }, {
          title: '正向用量(m³)',
          dataIndex: 'readDosage'
        }, {
          title: '反向用量(m³)',
          dataIndex: 'reverseDosage'
        }, {
          title: '净用量(m³)',
          dataIndex: 'totalDosage'
        }]
      } else if (this.queryParams.dataType === '3') {
        this.queryParams.startTime = this.timevalue[0]
        this.queryParams.endTime = this.timevalue[1]
        this.columns = [{
          title: '采集时间',
          dataIndex: 'readDateMonth',
          width: 200
        }, {
          title: '正向用量(m³)',
          dataIndex: 'readDosage'
        }, {
          title: '反向用量(m³)',
          dataIndex: 'reverseDosage'
        }, {
          title: '净用量(m³)',
          dataIndex: 'totalDosage'
        }]
      }
      this.getList()
      this.getEchartsData()

    },
    // 渲染图表
    renderChart() {
      let days = []
      let startTime = this.queryParams.startTime
      let endTime = this.queryParams.endTime
      if (this.queryParams.dataType === '1') {
        let newStartTime = moment(startTime).format('YYYY-MM-DD HH:mm:ss')
        let newEndTime = moment(endTime).format('YYYY-MM-DD HH:mm:ss')
        days = getTwoTimeList(newStartTime, newEndTime)
        this.chartExtend.xAxis.data = days
      } else if (this.queryParams.dataType === '2') {
        let newStartTime = moment(startTime).format('YYYY-MM-DD')
        let newEndTime = moment(endTime).format('YYYY-MM-DD')
        days = getTwoDayList(newStartTime, newEndTime)
        this.chartExtend.xAxis.data = days
      } else if (this.queryParams.dataType === '3') {
        let newStartTime = moment(startTime).format('YYYY-MM')
        let newEndTime = moment(endTime).format('YYYY-MM')
        days = getTwoMonth(newStartTime, newEndTime)
        this.chartExtend.xAxis.data = days
      }
      this.initEchart()
    },
    // 获取纵坐标
    handleData() {
      let datalist = this.echartsList
      let readlistitem = []
      let reverselistitem = []
      let totallistitem = []
      for (var i = 0; i < datalist.length; i++) {
        if (this.queryParams.dataType == '1') {
          readlistitem.push([datalist[i].readDateN, datalist[i].readDosage == null ? "" : datalist[i].readDosage]);
          reverselistitem.push([datalist[i].readDateN, datalist[i].reverseDosage == null ? "" : datalist[i].reverseDosage]);
          totallistitem.push([datalist[i].readDateN, datalist[i].totalDosage == null ? "" : datalist[i].totalDosage]);
        } else if (this.queryParams.dataType == '2') {
          readlistitem.push([datalist[i].readDateDay, datalist[i].readDosage == null ? "" : datalist[i].readDosage]);
          reverselistitem.push([datalist[i].readDateDay, datalist[i].reverseDosage == null ? "" : datalist[i].reverseDosage]);
          totallistitem.push([datalist[i].readDateDay, datalist[i].totalDosage == null ? "" : datalist[i].totalDosage]);
        } else if (this.queryParams.dataType == '3') {
          readlistitem.push([datalist[i].readDateMonth, datalist[i].readDosage == null ? "" : datalist[i].readDosage]);
          reverselistitem.push([datalist[i].readDateMonth, datalist[i].reverseDosage == null ? "" : datalist[i].reverseDosage]);
          totallistitem.push([datalist[i].readDateMonth, datalist[i].totalDosage == null ? "" : datalist[i].totalDosage]);
        }
      }
      let seriesItem = {
        name: '正向用量', // 系列名称
        type: 'line', // 类型：线
        smooth: true,
        data: readlistitem, // 数据
        showSymbol: false,
        markPoint: {
          // 特殊标注文字v/
          label: {
            normal: {
              show: true,
              //position: 'top', // 文字位置
              // 显示的文字
              formatter: '{b}：{c}',
            }
          },
          // 触发操作
          tooltip: {
            show: true, // 是否显示
            formatter: '{b}：{c}', // 内容格式器 a（系列名称），b（类目值），c（数值）, d（无）
            trigger: 'item', // 触发类型，默认数据触发，见下图，可选为：'item' | 'axis'
          },
        },
        // 折线图圆点
        label: {
          normal: {
            show: false,
            formatter: '{c}',
            textStyle: {
              color: '#000' // 文字颜色
            }
          }
        },
      }
      let readSeriesItem = {
        name: '反向用量', // 系列名称
        type: 'line', // 类型：线
        smooth: true,
        data: reverselistitem, // 数据
        showSymbol: false,
        markPoint: {
          // 特殊标注文字v/
          label: {
            normal: {
              show: true,
              //position: 'top', // 文字位置
              // 显示的文字
              formatter: '{b}：{c}',
            }
          },
          // 触发操作
          tooltip: {
            show: true, // 是否显示
            formatter: '{b}：{c}', // 内容格式器 a（系列名称），b（类目值），c（数值）, d（无）
            trigger: 'item', // 触发类型，默认数据触发，见下图，可选为：'item' | 'axis'
          },
        },
        // 折线图圆点
        label: {
          normal: {
            show: false,
            formatter: '{c}',
            textStyle: {
              color: '#000' // 文字颜色
            }
          }
        },
      }
      let totalSeriesItem = {
        showSymbol: false,
        name: '净用量', // 系列名称
        type: 'line', // 类型：线
        smooth: true,
        data: totallistitem, // 数据
        markPoint: {
          // 特殊标注文字v/
          label: {
            normal: {
              show: true,
              //position: 'top', // 文字位置
              // 显示的文字
              formatter: '{b}：{c}',
            }
          },
          // 触发操作
          tooltip: {
            show: true, // 是否显示
            formatter: '{b}：{c}', // 内容格式器 a（系列名称），b（类目值），c（数值）, d（无）
            trigger: 'item', // 触发类型，默认数据触发，见下图，可选为：'item' | 'axis'
          },
        },
        // 折线图圆点
        label: {
          normal: {
            show: false,
            formatter: '{c}',
            textStyle: {
              color: '#000' // 文字颜色
            }
          }
        },
      }
      this.chartExtend.series.push(seriesItem);
      this.chartExtend.series.push(readSeriesItem);
      this.chartExtend.series.push(totalSeriesItem);
      this.initEchart()
    },
    // 图表数据处理
    getEchartsData() {
      getTerminalDosageList(this.queryParams).then(response => {
        if (response.code === 200) {
          this.echartsList = response.data
          this.renderChart()
          this.handleData()
        }
      });
    },
    // 重置表单
    resetQuery() {
      this.timevalue = [moment().subtract(7, 'days').format('YYYY-MM-DD'), moment().subtract(1, 'day').format('YYYY-MM-DD')]
      this.queryParams = {
        pageNum: 1,
        pageSize: 20,
        startTime: moment().subtract(7, 'days').format('YYYY-MM-DD'),
        endTime: moment().subtract(1, 'day').format('YYYY-MM-DD'),
        interval: '',
        dataType: '2',
        location_nb: this.queryParams.location_nb,
      }
      this.dayDataList = []
      this.monthDataList = []
      this.handleQuery()
    },
    // 获取表格数据
    getList() {
      this.loading = true;
      getPageList(this.queryParams).then(response => {
        if (response.code === 200) {
          this.dataList = response.rows
          this.loading = false;
          this.total = response.total
        }
      });
    },
    // 切换类型
    dataTypeSelectChange() {
      let now = new Date();
      this.timevalue = [moment(now).format('YYYY-MM-DD 00:00:00'), moment(now).format('YYYY-MM-DD 23:59:59')];
      switch (this.queryParams.dataType) {
        // 实时数据
        case '1':
          this.timevalue = [
            moment(this.timevalue[0]).format('YYYY-MM-DD 00:00:00'),
            moment(this.timevalue[1]).format('YYYY-MM-DD 23:59:59')
          ]
          break;
        // 日报表
        case '2':

          this.timevalue = [
            moment(this.timevalue[0]).subtract(5, "days").format('YYYY-MM-DD'),
            moment(this.timevalue[1]).subtract(1, "days").format('YYYY-MM-DD')
          ]
          break;
        // 月报表
        case '3':
          this.timevalue = [
            moment(this.timevalue[0]).subtract(3, "months").format('YYYY-MM'),
            moment(this.timevalue[1]).subtract(1, "months").format('YYYY-MM')
          ]
          break;
      }
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('datastatistics/terminalXbStatisticAnalysis/exportDayOrMonth', {
        ...this.queryParams,
      }, `户表用量统计数据.xlsx`)
    }
  }

}
</script>

<style scoped lang="scss">
.form_col {
  width: 90%;

  ::v-deep .el-form {
    width: 100%;
  }

  ::v-deep .el-form-item {
    width: 30%;
  }
}

.form_query {
  width: 10%;
  text-align: right;
}
</style>
